class Shop extends PIXI.Container {
    constructor(uimanager, option, callback) {
        super();

        this.uimanager = uimanager;
        this.callback = callback;
        this.resolveAmout = 0;
        this.option = option || {isSell:true};

        // 添加底框
        const totalWidth = 160;
        const frame = new PIXI.smooth.SmoothGraphics();
        frame.beginFill(0x908058, 1);
        frame.lineStyle({ color: 0x2D2D2E, width: 1, alignment: 1 });
        frame.drawRoundedRect(0,0,totalWidth,24,20);
        frame.beginFill(0xE0E0C0, 1);
        frame.lineStyle({ color: 0xC0C0A8, width: 0, alignment: 1 });
        frame.drawRoundedRect(2,2,totalWidth-4,20,20);
        frame.endFill();
        frame.x = 410 - 160;
        frame.y = -36;
        this.addChild(frame);

        // 添加金币数
        const numLiteral = global.bag.gold+"$";
        this._gold = new PIXI.Text(numLiteral, numberStyle);
        this._gold.resolution = 2;
        this._gold.y = -32;
        this.addChild(this._gold);

        this.updateBag();
        this.addChild(global.bag);
        global.bag.selectOpation(0);

        this.x = (uimanager.realScreen.width - this.width) / 2;
        this.y = (uimanager.realScreen.height - this.height) / 2;
        uimanager.addChild(this);

        this._attach = global.bag;
    }

    updateBag() {
        const shop = this;

        shop._gold.text = global.bag.gold+"$";
        const numSize = PIXI.TextMetrics.measureText(shop._gold.text, numberStyle).width;
        shop._gold.x = 410 - numSize - 6;

        const tmp = global.bag.opationIndex;
        if(shop._numCtrl) {
            shop.removeChild(shop._numCtrl);
            shop._attach = global.bag;
        }

        function checkCanUse() {
            return true;
        }

        global.bag.setup(
            checkCanUse,
            function(item) {
                // 得到做大操作数量
                const maxAmount = shop.option.isSell ?
                    global.bag.exist(item.url) :
                    item.maxAmount - global.bag.exist(item.url);

                // 添加数量控件
                shop._numCtrl = new ShopNumber(shop.uimanager, shop, item, maxAmount, shop.option.isSell);
                shop._attach = shop._numCtrl;
                shop._numCtrl.x = shop.width - 100;
                shop._numCtrl.y = shop.height - 20;
                shop.addChild(shop._numCtrl);
            },
            function() {
                // 关闭商店
                shop.callback(shop.resolveAmout);
                shop.uimanager.removeChild(shop);
            }, false, true, this.option.isSell ? 0.5 : 1, this.option.items, tmp);
    }

    keyDown(key) {
        this._attach.keyDown(key);
    }
}

class ShopNumber extends PIXI.Container {
    constructor(uimanager, shop, item, opMaxAmount, isSell) {
        super();

        this.uimanager = uimanager;
        this.shop = shop;
        this.item = item;
        this.isSell = isSell;
        this.maxAmount = opMaxAmount;
        this._current = 0;
        this._index = 0;
        this._numbers = new PIXI.Container();

        // 计算宽度
        const maxAmount = item.maxAmount;
        const maxAmountString = maxAmount+"";
        this._singleSize = PIXI.TextMetrics.measureText("0", numberStyle).width;
        const totalWidth = this._singleSize * Math.max(2, maxAmountString.length) + 20;

        // 添加底框
		const frame = new PIXI.Graphics();
		frame.beginFill(0x908058, 1);
		frame.lineStyle({ color: 0x2D2D2E, width: 1, alignment: 1 });
		frame.drawRect(0,0,totalWidth,24);
		frame.beginFill(0xE0E0C0, 1);
		frame.lineStyle({ color: 0xC0C0A8, width: 0, alignment: 1 });
		frame.drawRect(2,2,totalWidth-4,20);
		frame.endFill();
        this.addChild(frame);

        // 添加x
        const literal = "×";
		const text = new PIXI.Text(literal, xStyle);
		text.resolution = 2;
		text.x = 5;
		text.y = 4;
		this.addChild(text);

        // 更新数字
        this.addChild(this._numbers);
        this.update();
        this.setNumber(1);
    }

    update() {
        const oldTexts = [];
        for(var i = 0; i < this._numbers.children.length; i++) {
            oldTexts.push(this._numbers.children[i].text);
            this._numbers.removeChild(this._numbers.children[i]);
            i--;
        }

        // 添加每个数字
        const currentAmountString = (this._current+"").padLeft(Math.max(2, (this.item.maxAmount+"").length), "0");
        var amountX = 15;
        for(var i = 0; i < currentAmountString.length; i++) {
            const isSelected = (currentAmountString.length - 1 - this._index) == i;
            const numLiteral = currentAmountString[i];
            const numText = new PIXI.Text(numLiteral, isSelected ? numberSelectedStyle : numberStyle);
            numText.resolution = 2;
            numText.x = amountX + (isSelected ? -1 : 0);
            numText.y = isSelected ? 3 : 4;
            numText.text = oldTexts[i] || "0";
            this._numbers.addChild(numText);

            amountX = amountX + this._singleSize;
        }
    }

    getNumber() {
        var numString = "";
        for(var i = 0; i < this._numbers.children.length; i++) {
            numString = numString + this._numbers.children[i].text;
        }

        return parseInt(numString);
    }

    setNumber(value) {
        value = Math.max(1, value);
        value = Math.min(this.maxAmount, value);

        const valueStr = (value+"").padLeft(Math.max(2, (this.item.maxAmount+"").length), "0");
        for(var i = 0; i < valueStr.length; i++) {
            this._numbers.children[i].text = valueStr[i]+"";
        }
    }

    keyDown(key) {
        switch(key) {
            case "left": 
                // 选择index
                this._index = Math.min(Math.max(2, (this.item.maxAmount+"").length) - 1, this._index + 1);
                this.update();
                break;
            case "right": 
                this._index = Math.max(0, this._index - 1);
                this.update();
                break;
            case "up":
                // 增加购买或贩售数量
                this.setNumber(this.getNumber() + parseInt("1".padRight(this._index + 1,"0")));
                break;
            case "down": 
                // 减少购买或贩售数量
                this.setNumber(this.getNumber() - parseInt("1".padRight(this._index + 1,"0")));
                break;
            case "z":
                // 隐藏背包
                this.uimanager.removeChild(this.shop);

                // 弹出售价和确认框
                const check = new ShopCheck(this.shop, this.uimanager, this.uimanager.lastTalker, this.item, this.getNumber(), this.isSell);
                check.x = this.uimanager.realScreen.width;
                check.y = 50;
                this.uimanager.addChild(check);
                createjs.Tween.get(check.position).to({x:this.uimanager.realScreen.width - 410,y:50},200);
                break;
            case "x":
                // 取消选框
                this.shop._attach = global.bag;
                this.shop.removeChild(this);
                break;
        }
    }
}

class ShopCheck extends PIXI.Container {
    constructor(shop, uimanager, talker, item, itemAmount, isSell) {
        super();

        this.item = item;
        this.itemAmount = itemAmount;
        this.shop = shop;
        this.uimanager = uimanager;
        this.amount = parseInt((item.price * itemAmount) / (isSell ? 2 : 1));
        this.isSell = isSell;

		// 创建对话框
		const frame = new PIXI.smooth.SmoothGraphics();
		frame.beginFill(0x686028, 1);
		frame.lineStyle({ color: 0x181818, width: 1, alignment: 0 });
		frame.drawRoundedRect(0,0,460,100,50);
		frame.beginFill(0xE0E0C0, 1);
		frame.lineStyle({ color: 0x686028, width: 0, alignment: 0 });
		frame.drawRoundedRect(2,2,460-4,100-4,50);
		frame.endFill();
        this.addChild(frame);

		// 设置对话位置	
		const richText = new PIXI.Text(`如果是这样,${(isSell ? "卖出" : "购买")}${item.name}×${itemAmount}\n就${this.amount}金币吧。`, talkStyle);
		richText.resolution = 2;
		richText.position.set(30,10);
		this.addChild(richText);	

		// 得到talker半身像
        if(talker) {
            const avater = PIXI.Texture.from(talker.avater);
            const spriteImage = new PIXI.Sprite(avater);
            spriteImage.x = 410 - 156;
            spriteImage.y = -50;
            this.addChild(spriteImage);
        }

        // 添加菜单
		this.menu = new Menu("MENU", 220);
		this.menu.addItem(new MenuItem("确定"));
		this.menu.addItem(new MenuItem("取消"));
        this.menu.selectedIndex = 0;
        this.menu.x = 400 - 220;
		this.menu.y = 116;
        this.addChild(this.menu);
    }

    async keyDown(key) {
        switch(key) {
            case "up": this.menu.up(); break;
            case "down": this.menu.down(); break;
            case "z":
                if(this.menu.selectedIndex == 0) {
                    // 如果是售卖
                    if(this.isSell) {
                        // 从背包中移除物品
                        global.bag.remove(this.item.url, this.itemAmount);

                        // 添加金币
                        global.bag.gold += this.amount;

                        // 播放金币到账声音

                    } else {
                        // 否则是购买，检查金币数量
                        if(global.bag.gold<this.amount) {
                            this.uimanager.removeChild(this);
                            // 金币数量不足提示
                            await L2D.UIManager.talk(L2D.UIManager.lastTalker, "你的金币不够哦。");
                        }
                        else {
                            // 向背包中添加物品
                            global.bag.add(this.item.url, this.itemAmount);

                            // 减少金币
                            global.bag.gold -= this.amount;

                            // 播放金币扣除声音
                        }
                    }

                    // 添加处理数量
                    this.shop.resolveAmout += this.itemAmount;
                    
                    // 调用callback
                    if(this.shop.option && this.shop.option.callback)
                        this.shop.option.callback(this.item.url, this.itemAmount);
                }
            case "x":
                // 更新背包
                this.shop.updateBag();
                // 返回上级菜单
                this.uimanager.addChild(this.shop);
                // 
                this.uimanager.removeChild(this);
                break;
        }
    }
}